package cn.changeforyou.web.plugin.page.config;

import cn.changeforyou.web.plugin.page.LocalThreadPageUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author zhyu
 * @date 2019/12/28 10:29 用于自动拦截.page的请求， 设置分页， 以后分页就只需要把url设计为*.page的形式， controller， service就当没有分页使用就可以了
 */
@Component
public class PageParamsInterceptor implements HandlerInterceptor {

    @Autowired
    private PageProperties pageProperties;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String parameter1 = request.getParameter(pageProperties.getPageNumberName());
            String parameter2 = request.getParameter(pageProperties.getPageSizeName());
            int pageSize = pageProperties.getPageSize();
            int pageNumber = pageProperties.getPageNumber();
            if (parameter1 != null) {
                pageNumber = receiveNumber(parameter1, "pageNumber");
            }
            if (parameter2 != null) {
                pageSize = receiveNumber(parameter2, "pageSize");
            }
            if (pageNumber < 0 || pageSize < 0) {
                BeanPropertyBindingResult beanPropertyBindingResult = new BeanPropertyBindingResult(parameter1, parameter2);
                beanPropertyBindingResult.addError(new ObjectError("", "pageNumber, pageSize不能小于0"));
                throw new BindException(beanPropertyBindingResult);
            }
            LocalThreadPageUtil.setPageNumber(pageNumber);
            LocalThreadPageUtil.setPageSize(pageSize);
        }
        return true;
    }
    
    private Integer receiveNumber(String value, String name) throws BindException {
        try{
            return Integer.valueOf(value);
        }catch (NumberFormatException e) {
            BeanPropertyBindingResult beanPropertyBindingResult = new BeanPropertyBindingResult(value, name);
            beanPropertyBindingResult.addError(new ObjectError(name, name + "应该是int类型的值"));
            throw new BindException(beanPropertyBindingResult);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        if (handler instanceof HandlerMethod) {
            LocalThreadPageUtil.clear();
        }
    }
}
